package com.google.code.sms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

import com.google.code.sms.Logger;
import com.google.code.sms.service.metadata.MetaData;
import com.google.code.sms.service.metadata.MetaData.DirectoryMediaType;

/**
 * Provides database services for directory meta-data.
 *
 * @author Scott Ware
 */

public class DirectoryMetaDataDao extends AbstractDao {
    
    private static final Logger LOG = Logger.getLogger("DirectoryMetaDataDao");
    private static final String COLUMNS = "media_element_id, media_type, cover_art_path";
    public final RowMapper rowMapper = new DirectoryMetaDataDao.DirectoryMetaDataMapper();

    /**
     * Returns the directory meta-data for the given media element ID.
     *
     * @param id The media element ID.
     * @return The directory meta-data or null.
     */
    public MetaData getMetaData(int id) {
        return queryOne("select " + COLUMNS + " from directory_metadata where media_element_id=?", rowMapper, id);
    }
    
     /**
     * Creates or updates directory meta-data.
     *
     * @param metadata The directory meta-data to create/update.
     */
    public synchronized void createOrUpdate(MetaData metadata)
    {   
        if(metadata.getMediaElementID() == null)
        {
            LOG.warn("Media Element ID not defined");
            return;
        }
        
        String sql = "update directory_metadata set "
                + "media_type=?,"
                + "cover_art_path=?"
                + "where media_element_id=?";

        int n = update(sql,
                metadata.getDirectoryMediaType(), metadata.getCoverArtPath(), metadata.getMediaElementID());

        if (n == 0) {

            update("insert into directory_metadata (" + COLUMNS + ") values (" + questionMarks(COLUMNS) + ")",
                metadata.getMediaElementID(), metadata.getDirectoryMediaType(), metadata.getCoverArtPath());
        }
    }

    public void deleteMetaData(int id) {
        update("delete from directory_metadata where media_element_id=?", id);
        update("checkpoint");
    }
    
    private static class DirectoryMetaDataMapper implements ParameterizedRowMapper<MetaData> {

        @Override
        public MetaData mapRow(ResultSet rs, int rowNum) throws SQLException 
        {
            MetaData metadata = new MetaData();
            
            metadata.setMediaElementID(rs.getInt(1));
            metadata.setDirectoryMediaType(DirectoryMediaType.valueOf(rs.getString(2)));
            metadata.setCoverArtPath(rs.getString(3));
            
            return metadata;
        }
    }
    
    public static RowMapper getRowMapper()
    {
        return new DirectoryMetaDataDao.DirectoryMetaDataMapper();
    }
}
